package com.example.backend.controller.user;


import cn.hutool.core.convert.Convert;
import com.example.backend.dto.request.UpdateUserInfo;
import com.example.backend.entitly.mysql.user.Users;
import com.example.backend.enums.ResultCodeEnum;
import com.example.backend.service.mysql.user.UsersService;
import com.example.backend.utils.ResultJson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Tag(name = "用户管理", description = "包含用户信息查询，修改等")
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Validated
@Transactional(rollbackFor = Exception.class)
public class UserController {

    private final UsersService userService;

    public static Integer getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return (Integer) authentication.getPrincipal();
        }
        throw new UsernameNotFoundException(ResultCodeEnum.NOT_LOGIN.getMessage());
    }

    @Operation(summary = "获取用户信息", description = "获取用户信息")
    @PreAuthorize("hasAnyAuthority('user:read')")
    @GetMapping("/user")
    public ResultJson<?> getUserInfo() {
        Integer principal = getUser();
        Users byId = userService.getByUserId(principal);
        return ResultJson.success(byId);
    }

    @Operation(summary = "修改用户信息", description = "修改用户信息")
    @PreAuthorize("hasAnyAuthority('user:update')")
    @PutMapping("/update")
    public ResultJson<?> updateUserInfo(UpdateUserInfo updateUserInfo) {
        Integer principal = getUser();
        updateUserInfo.setUserId(Long.valueOf(principal));
        Users convert = Convert.convert(Users.class, updateUserInfo);
        userService.saveOrUpdate(convert);
        return ResultJson.success(ResultCodeEnum.USER_UPDATE_SUCCESS.getMessage());
    }

    @Operation(summary = "删除用户信息", description = "删除用户信息")
    @PreAuthorize("hasAnyAuthority('user:delete')")
    @DeleteMapping("/delete")
    public ResultJson<?> deleteUserInfo() {
        // Todo: 2023/9/23 删除用户
        Integer principal = getUser();
        Boolean aBoolean = userService.removeByUserId(Long.valueOf(principal));
        if (!aBoolean) {
            return ResultJson.fail(ResultCodeEnum.USER_DELETE_FAIL.getCode(), ResultCodeEnum.USER_DELETE_FAIL.getMessage());
        }
        return ResultJson.success("删除成功，可在一段时间内部取消");
    }

    @Operation(summary = "恢复用户信息", description = "恢复用户信息")
    @PreAuthorize("hasAnyAuthority('user:restore')")
    @GetMapping("/restore")
    public ResultJson<?> restoreUserInfo() {
        // Todo: 2023/9/23 恢复用户
        Integer principal = getUser();
        Users byId = userService.getByRemoveId(Long.valueOf(principal));
        if (byId == null) {
            return ResultJson.fail(ResultCodeEnum.USER_NOT_DELETED.getCode(), ResultCodeEnum.USER_NOT_DELETED.getMessage());
        }
        if (UserAdminController.deleteTime(byId)) {
            return ResultJson.fail(ResultCodeEnum.USER_NOT_RESTORED.getCode(), ResultCodeEnum.USER_NOT_RESTORED.getMessage());
        }
        Boolean aBoolean = userService.cancelRemove(Long.valueOf(principal));
        if (!aBoolean) {
            return ResultJson.fail(ResultCodeEnum.USER_RESTORE_FAIL.getCode(), ResultCodeEnum.USER_RESTORE_FAIL.getMessage());
        }
        return ResultJson.success("恢复成功");
    }
}
